package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.dto.PPTDTO;
import com.eduplatform.entity.PPT;
import com.eduplatform.entity.School;
import com.eduplatform.entity.Subject;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.PPTMapper;
import com.eduplatform.service.PPTService;
import com.eduplatform.service.SchoolService;
import com.eduplatform.service.SubjectService;
import com.eduplatform.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PPT课件服务实现类
 */
@Service
public class PPTServiceImpl extends ServiceImpl<PPTMapper, PPT> implements PPTService {

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private SchoolService schoolService;

    @Override
    public Page<PPTDTO> listPPTs(int page, int size, String keyword, Long subjectId, Integer educationLevel,
            Long schoolId) {
        Page<PPT> pptPage = new Page<>(page, size);
        LambdaQueryWrapper<PPT> queryWrapper = new LambdaQueryWrapper<>();

        // 设置查询条件
        queryWrapper.eq(PPT::getIsDeleted, 0);

        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(PPT::getTitle, keyword)
                    .or()
                    .like(PPT::getDescription, keyword)
                    .or()
                    .like(PPT::getTags, keyword);
        }

        if (subjectId != null) {
            queryWrapper.eq(PPT::getSubjectId, subjectId);
        }

        if (educationLevel != null) {
            queryWrapper.eq(PPT::getEducationLevel, educationLevel);
        }

        if (schoolId != null) {
            queryWrapper.and(wrapper -> wrapper.eq(PPT::getSchoolId, schoolId).or().isNull(PPT::getSchoolId));
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(PPT::getCreateTime);

        // 分页查询
        Page<PPT> result = page(pptPage, queryWrapper);

        // 转换为DTO
        Page<PPTDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(result, dtoPage, "records");

        List<PPTDTO> dtoList = new ArrayList<>();
        for (PPT ppt : result.getRecords()) {
            PPTDTO dto = convertToDTO(ppt);
            dtoList.add(dto);
        }

        dtoPage.setRecords(dtoList);
        return dtoPage;
    }

    @Override
    public PPTDTO getPPTById(Long id) {
        PPT ppt = getById(id);
        if (ppt == null || ppt.getIsDeleted() == 1) {
            return null;
        }

        return convertToDTO(ppt);
    }

    @Override
    public boolean addPPT(PPTDTO pptDTO) {
        PPT ppt = new PPT();
        BeanUtils.copyProperties(pptDTO, ppt);

        // 设置默认值
        ppt.setCreateTime(new Date());
        ppt.setUpdateTime(new Date());
        ppt.setIsDeleted(0);
        ppt.setDownloadCount(0);
        ppt.setViewCount(0);

        return save(ppt);
    }

    @Override
    public boolean updatePPT(PPTDTO pptDTO) {
        PPT ppt = getById(pptDTO.getId());
        if (ppt == null || ppt.getIsDeleted() == 1) {
            return false;
        }

        BeanUtils.copyProperties(pptDTO, ppt);
        ppt.setUpdateTime(new Date());

        return updateById(ppt);
    }

    @Override
    public boolean deletePPT(Long id) {
        PPT ppt = getById(id);
        if (ppt == null) {
            return false;
        }

        ppt.setIsDeleted(1);
        ppt.setUpdateTime(new Date());

        return updateById(ppt);
    }

    @Override
    public List<PPTDTO> getHotPPTs(int limit) {
        LambdaQueryWrapper<PPT> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PPT::getIsDeleted, 0)
                .orderByDesc(PPT::getDownloadCount)
                .orderByDesc(PPT::getViewCount)
                .last("LIMIT " + limit);

        List<PPT> pptList = list(queryWrapper);
        return pptList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public List<PPTDTO> getLatestPPTs(int limit) {
        LambdaQueryWrapper<PPT> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PPT::getIsDeleted, 0)
                .orderByDesc(PPT::getCreateTime)
                .last("LIMIT " + limit);

        List<PPT> pptList = list(queryWrapper);
        return pptList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public boolean viewPPT(Long id) {
        PPT ppt = getById(id);
        if (ppt == null || ppt.getIsDeleted() == 1) {
            return false;
        }

        ppt.setViewCount(ppt.getViewCount() + 1);
        return updateById(ppt);
    }

    @Override
    public boolean downloadPPT(Long id) {
        PPT ppt = getById(id);
        if (ppt == null || ppt.getIsDeleted() == 1) {
            return false;
        }

        ppt.setDownloadCount(ppt.getDownloadCount() + 1);
        return updateById(ppt);
    }

    /**
     * 将PPT实体转换为DTO
     * 
     * @param ppt PPT实体
     * @return PPT DTO
     */
    private PPTDTO convertToDTO(PPT ppt) {
        PPTDTO dto = new PPTDTO();
        BeanUtils.copyProperties(ppt, dto);

        // 设置标签列表
        if (StringUtils.hasText(ppt.getTags())) {
            dto.setTagList(Arrays.asList(ppt.getTags().split(",")));
        } else {
            dto.setTagList(new ArrayList<>());
        }

        // 设置用户名
        User user = userService.getById(ppt.getUserId());
        if (user != null) {
            dto.setUserName(user.getNickname());
        }

        // 设置学科名称
        Subject subject = subjectService.getById(ppt.getSubjectId());
        if (subject != null) {
            dto.setSubjectName(subject.getName());
        }

        // 设置学校名称
        if (ppt.getSchoolId() != null) {
            School school = schoolService.getById(ppt.getSchoolId());
            if (school != null) {
                dto.setSchoolName(school.getName());
            }
        } else {
            dto.setSchoolName("所有学校");
        }

        // 设置教育阶段名称
        switch (ppt.getEducationLevel()) {
            case 1:
                dto.setEducationLevelName("小学");
                break;
            case 2:
                dto.setEducationLevelName("初中");
                break;
            case 3:
                dto.setEducationLevelName("高中");
                break;
            case 4:
                dto.setEducationLevelName("大学");
                break;
            default:
                dto.setEducationLevelName("未知");
                break;
        }

        return dto;
    }
}